const initialState = {
  allChannels: [] as ChannelType[],
  userChannels: [] as ChannelType[],
  currentId: 0,
};

export type ActionType =
  | { type: 'channel/saveAllChannel'; payload: ChannelType[] }
  | { type: 'channel/saveUserChannel'; payload: ChannelType[] }
  | { type: 'channel/addUserChannel'; payload: number }
  | { type: 'channel/delUserChannel'; payload: number }
  | { type: 'channel/setCurrentId'; payload: number };

const channelReducer = (state = initialState, action: ActionType): typeof initialState => {
  switch (action.type) {
    case 'channel/saveAllChannel':
      return {
        ...state,
        allChannels: action.payload,
      };
    case 'channel/saveUserChannel':
      return {
        ...state,
        userChannels: action.payload,
      };

    case 'channel/addUserChannel':
      const newItem = state.allChannels.find((item) => item.id === action.payload);
      return {
        ...state,
        userChannels: [...state.userChannels, newItem as ChannelType].sort((a, b) => a.id - b.id),
      };

    case 'channel/delUserChannel':
      return {
        ...state,
        userChannels: state.userChannels.filter((item) => item.id !== action.payload),
      };

    case 'channel/setCurrentId':
      return {
        ...state,
        currentId: action.payload,
      };

    default:
      return state;
  }
};

export default channelReducer;

export interface ChannelType {
  id: number;
  name: string;
}
